<template>
  <div class="app-container">
    <template v-if="!showDesignIndex">
    <div class="search-container">
      <el-form ref="form" :model="queryParams" :inline="true">
        <el-form-item prop="keywords" label="模板名称">
          <el-input
            v-model="queryParams.keywords"
            placeholder="模板名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery" icon="el-icon-search">搜索</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <template #header>
        <el-button type="success" @click="openDialog()"
          ><i class="el-icon-circle-plus"></i> 新增</el-button>
        <el-button
          type="danger"
          :disabled="ids.length === 0"
          @click="handleDelete()"
          ><i class="el-icon-delete"></i> 删除</el-button>
      </template>

      <el-table
        v-loading="loading"
        :data="dataList"
        highlight-current-row
        border
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="模板名称" prop="name">
          <template #default="scope">
            <p>{{ scope.row.name }}<el-tag style="margin-left: 10px; cursor: pointer;" @click="renameDialog(scope.row)">重命名</el-tag></p>
            
          </template>
        </el-table-column>
        <el-table-column label="所属应用" prop="applicationName" width="200"/>
        <el-table-column label="模板封面路径" prop="coverPath" width="150"/>
        <el-table-column fixed="right" label="操作"  min-width="300" width="390">
          <template #default="scope">
            <el-button type="warning" size="small" link @click="goReportDesign(scope.row)"><i class="el-icon-edit"></i> 编辑</el-button>
            <el-button type="danger" size="small" link @click="handleDelete(scope.row.id)"><i class="el-icon-delete"></i> 删除</el-button>
            <el-button type="primary" size="small" link @click="openEditApplication(scope.row)"><i class="el-icon-edit"></i> 设置应用</el-button>
            <el-button type="primary" size="small" link @click="coverPdf(scope.row.id)" v-show="scope.row.coverPath"><i class="el-icon-view"></i> 预览封面</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParams.pageNum"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="50"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 模板表单弹窗 -->
    <el-dialog
      :visible.sync="dialog.visible"
      :title="dialog.title"
      width="80%" :close-on-click-modal="false"
      :before-close="closeDialog"
    >
      <el-form
        ref="userFormRef"
        :model="formData"
        :rules="rules"
        label-width="150px"
      >
        <el-form-item label="模板名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="模板文件" v-if="formData.id">
          <el-upload
            class="upload-dialog"
            ref="upload"
            :action="uploadAction"
            :show-file-list="false"
            :on-change="submitUpload"
            :on-success="uploadFileSuccess"
            :headers="headers"
            :auto-upload="false">
            <el-button slot="trigger" style="margin-left: 5px;" type="success">上传文件</el-button>
            <div slot="tip" class="el-upload__tip"></div>
          </el-upload>
          <span v-for="d in formData.fileNameList" :key="d" style="margin-left: 5px;">{{ d }}</span>
        </el-form-item>

        <el-form-item label="模板内容" prop="content">
          <codemirror
            ref="codemirrorEdit"
            v-model="codeContent"
            :options="cmOptions"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="addOrUpdate">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      :visible.sync="previewDialog.visible"
      :title="previewDialog.title"
      width="900px" :close-on-click-modal="false"
      :before-close="closePreviewDialog"
    >
      <iframe ref="pdfCotainer" :src="pdfUrl" width="100%" height="650px"></iframe>
    </el-dialog>

    <el-dialog
			:visible.sync="editDialog"
			title="编辑所属应用"
			width="400px"
			:close-on-click-modal="false"
			:before-close="closeEditApplication">
      <el-form
        ref="userFormRef"
        :model="formData"
        :rules="rules"
        label-width="100px">
        <el-form-item label="所属应用" prop="applicationId">
          <el-select v-model="formData.applicationId">
            <el-option v-for="field in applicationList" :key="field.id" :label="field.name" :value="field.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="saveApplication">确 定</el-button>
          <el-button @click="closeEditApplication">取 消</el-button>
        </div>
      </template>
		</el-dialog>

    <el-dialog :visible.sync="editTemplateNameDialog" title="修改模板名称" width="400px" :close-on-click-modal="false" :before-close="closeRenameDialog">
      <el-form ref="templateNameFormRef" label-width="100px">
        <el-form-item label="模板名称" prop="templateName">
          <el-input type="text" v-model="templateName"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="rename">确 定</el-button>
          <el-button @click="closeRenameDialog">取 消</el-button>
        </div>
      </template>
		</el-dialog>

    </template>

    <reportDesignIndex :checkedTemplate="checkedTemplate" v-if="showDesignIndex" @close="closeDesign"></reportDesignIndex>

  </div>
</template>

<script>

import reportDesignIndex from '@/views/reporting/reportDesign'
import { Session } from '@/utils/storage'
import dfApplicationApi from '@/api/analysis/application';
import reportTemplateApi from '@/api/report/template'
import { codemirror } from 'vue-codemirror'
import 'codemirror/lib/codemirror.css'

import 'codemirror/mode/javascript/javascript.js'
import 'codemirror/mode/css/css.js'
import 'codemirror/mode/vue/vue.js'
import './setting.js'
export default {
	name: 'reportTemplateIndex',
  components: {
    codemirror,
    reportDesignIndex
  },
	data() {
		return {
			queryParams: {
        keywords: '',
        pageNum: 0,
        pageSize: 50,

      },
      total: 0,
      loading: false,
      dataList: [],
      ids: [],
      dialog: {},
      formData: {},
      rules: {},

      uploadAction: '',
      headers: {},
      cmOptions: {
        tabSize: 2, // tab
        styleActiveLine: true,
        lineNumbers: true,
        styleSelectedText: true,
        line: true,
        foldGutter: true,
        gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'],
        highlightSelectionMatches: { showToken: /\w/, annotateScrollbar: true },
        mode: 'text/html',
        hintOptions: {
          completeSingle: false
        },
        keyMap: 'sublime',
        matchBrackets: true,
        showCursorWhenSelecting: true,
        theme: 'monokai',
        // theme: 'solarized',
        extraKeys: { 'Ctrl': 'autocomplete' }
      },
      codeContent: '',

      previewDialog: {},
      pdfUrl: '',

      applicationList: [],
      editDialog: false,

      checkedTemplate: {},
      showDesignIndex: false,

      templateId: '',
      templateName: '',
      editTemplateNameDialog: false,
		};
	},
  codemirror () {
    return this.$refs.codemirrorEdit.codemirror
  },
  mounted () {
    this.headers = {
      Authorization: 'Bearer ' + localStorage.getItem('token')
    };
  },
  methods: {
    rename () {
      reportTemplateApi.updateName({
        id: this.templateId,
        name: this.templateName,
      }).then(res => {
        this.$message({ message: '模板名称修改成功！', type: 'success' });
        this.closeRenameDialog();
        this.handleQuery();
      })
    },
    renameDialog (row) {
      this.templateId = row.id;
      this.templateName = row.name;
      this.editTemplateNameDialog = true;
    },
    closeRenameDialog () {
      this.editTemplateNameDialog = false;
    },
    closeDesign () {
      this.showDesignIndex = false;
    },
    saveApplication () {
      reportTemplateApi.setDfApplication(this.formData.id, this.formData.applicationId).then(res => {
        this.editDialog = false;
        this.$message({ message: '模板所属应用设置成功！', type: 'success' });
				this.handleQuery();
      })
    },
    openEditApplication (row) {
      dfApplicationApi.list().then(res => {
        this.applicationList = res.data;
        this.editDialog = true;
        this.formData = row;
      })
    },
    closeEditApplication () {
      this.editDialog = false;
    },
    closePreviewDialog () {
      this.$set(this.previewDialog, 'visible', false);
    },
    coverPdf (id) {
      this.$set(this.previewDialog, 'title', '预览模板封面');
      this.$set(this.previewDialog, 'visible', true);
      reportTemplateApi.downloadCover(id).then(res => {
        const binaryData = [];
        binaryData.push(res);
        this.pdfUrl = window.URL.createObjectURL(new Blob(binaryData, {type: 'application/pdf'}));
        //var pdfCotainer = this.$refs.pdfCotainer;
        //pdfCotainer.height = document.documentElement.clientHeight;
      })
    },
    goReportDesign (row) {
      this.checkedTemplate = row;
      this.showDesignIndex = true;
      // let url = this.$router.resolve({
      //   path: "/reporting/reportDesign",
      //   query: {templateId: id }
      // })
      // //window.open(url.href);
      // window.location.href = url.href;

    },
    uploadFileSuccess () {
      this.$message({message: '文件上传成功！', type: 'success'});
    },
    submitUpload (file, fileList) {
      this.$refs.upload.submit();
    },
    handleQuery() {
      this.loading = true;
      let params = {
        number: this.queryParams.pageNum,
        size: this.queryParams.pageSize
      };
      reportTemplateApi.page(params).then((res) => {
        let data = res.data;
        this.dataList = data.content;
        this.total = data.count;
        this.loading = false;
      }).catch(() => {});
    },
    resetQuery() {
      this.queryParams = {
        keywords: '',
        pageNum: 0,
        pageSize: 50,
      };
      this.handleQuery();
    },
    
    addOrUpdate() {
      let that = this;
      
      if (this.formData.id) {
        this.formData.markdownContent = this.codeContent;
        reportTemplateApi.update(this.formData).then((res) => {
          this.$message({message: '模板更新成功！', type: 'success'});
          that.closeDialog();
        });
      } else {
        this.formData.content = this.codeContent;
        reportTemplateApi.add(this.formData).then((res) => {
          this.$message({message: '模板添加成功！', type: 'success'});
          that.closeDialog();
        });
      }
    },

    openDialog(id) {
      this.$set(this.dialog, 'visible', true);
      let that = this;
      this.uploadAction = process.env.VUE_APP_FILE_API_PREV + '/service-platform/template/upload-file/' + id;
      this.formData = {};
      this.$set(this.formData, 'content', '')
      this.codeContent = '';
      if (id) {
        this.$set(this.dialog, 'title', '编辑模板');
        reportTemplateApi.get(id).then((res) => {
          let data = res.data;
          that.codeContent = data.markdownContent;
          that.formData = data;
        });
      } else {
        this.$set(this.dialog, 'title', '新增模板');
        that.formData = {};
      }

    },
    closeDialog() {
      this.$set(this.dialog, 'visible', false);
      this.$set(this.dialog, 'title', '');
      this.handleQuery();
    },
    handleDelete(id) {
      if (id) {
        this.$confirm('此操作将永久删除数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          reportTemplateApi.delete(id).then((res) => {
            this.$message({message: '模板删除成功！', type: 'success'});
            this.handleQuery();
          }).catch(() => {});
        }).catch(() => {   
        });
      } else {

        this.$message.error('暂不支持批量删除模板！');
      }
    },
    handleSelectionChange(val) {
      this.ids = [];
      val.forEach(v => {
        this.ids.push(v.id);
      });
    },
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.handleQuery();
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.handleQuery();
    },
  },
  created() {
    this.handleQuery();
  }
};
</script>

<style scoped>
.block {
  margin-top: 10px;
  float: right;
  margin-bottom: 10px;
}
.CodeMirror-hints{
    z-index: 3000 !important;
}

/deep/.CodeMirror {
  height: 600px !important;
}
</style>